#Ui模块
from datetime import timedelta
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, get_jwt_identity, jwt_required
from extetion import db
from flask_cors import CORS, cross_origin
from Ctr_package.SCtr_User.SCtr_User_S import Ctr_User_S
from Ctr_package.SCtr_Super import SCtr_Super
from Ctr_package.SCtr_Mana import SCtr_Mana
from Ctr_package.SCtr_Film.SCtr_Film_M import SCtr_Film_M
from Ctr_package.SCtr_Film.SCtr_Film_C import SCtr_Film_C
from Ctr_package.SCtr_Comment.SCtr_Comment_C import SCtr_Comment_C
from Ctr_package.SCtr_Comment.SCtr_Comment_W import SCtr_Comment_W
from Ctr_package.SCtr_Mark.SCtr_Mark_C import SCtr_Mark_C
from Ctr_package.SCtr_Mark.SCtr_Mark_W import SCtr_Mark_W
from Ctr_package.SCtr_Re.SCtr_Re_C import SCtr_Re_C
from Ctr_package.SCtr_Re.SCtr_Re_W import SCtr_Re_W
from Ctr_package.SCtr_User.SCtr_User_M import SCtr_User_M

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:1234@localhost/film_remark'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
app.config['JWT_SECRET_KEY'] = 'film_remark'  # 用于签名JWT的密钥
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=60)  # 设置令牌的过期时间为60分钟
jwt = JWTManager(app)

cors_config = {
    r"/*": {"origins": ["https://example.com"]}
}
CORS(app, resources=cors_config)

user_today = 0#今日流动人数
user_regist =0#今日注册人数
manager_ban_block =0#今日管理员禁用用户数
user_ban_block=0#今日被禁用户数
film_love = 0#今日关注电影数

@app.route('/',methods=['GET'])
def hellow():
    return 'hellow'

#登录接口
@app.route('/login', methods=['POST'])
@cross_origin()  # 允许跨域请求
def login():
    data= request.json
    user_id = data.get('user_id')
    password = data.get('user_password')
    key = data.get('identity')
    login = None
    if key==0:#用户
        login = Ctr_User_S.login(user_id,password)
    elif key==1:#超管
        login = SCtr_Super.login(user_id,password)
    elif key==2:#管理员
        login = SCtr_Mana.login(user_id,password)
    if login:
        global user_today
        user_today += 1
        access_token = create_access_token(identity=user_id)
        return jsonify({"access_token":access_token}), 200
    else:
        return jsonify({"msg": "Invalid username or password"}), 401

#注册接口
@app.route('/register', methods=['POST'])
@cross_origin()  # 允许跨域请求
def register():
    data = request.json
    user_id = data.get('user_id')
    password = data.get('user_password')
    name = data.get('user_name')
    email = data.get('user_email')
    action = data.get("action")
    if action == "regist":
        verification_code = Ctr_User_S.register(user_id,email)
        if verification_code:
            return jsonify({"message": "Please verify your account", "verification_code": verification_code}), 201
        return jsonify({"message": "id or email wrong"}), 401
        
    verification_code=str(data.get('code'))#后端发送的验证码
    vetify = str(data.get('vetify_code'))#用户输入的验证码
    if vetify == verification_code:
        try:
            exist=Ctr_User_S.add_user(user_id,password,name,email)
            if exist:
                global user_regist
                user_regist +=1
                return jsonify({"message": "注册成功"}), 200
            else:
                return jsonify({"error": "创建失败"}), 400
        except Exception as e:
            return jsonify({"error": str(e)}), 500
    else: 
        return jsonify({"error": "验证码错误"}), 400

#超管管理管理员/用户
@app.route('/super_ma_user',methods = ['POST'])
@cross_origin()
@jwt_required()
def super_ma_user():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code == 0:#增加/删除用户
        id = data.get('id_be_done')
        password = data.get('user_password')
        email = data.get('email')
        name = data.get('name')
        if password:
            sign = Ctr_User_S.email_id_exist(id,email)
            if sign:
                sign2 = Ctr_User_S.add_user(id,password,name,email)
                if sign2:
                    return jsonify({"status":"successfully"})
                return jsonify({"status":"fail"})
            return jsonify({"status":"fail"})
        sign = Ctr_User_S.delete_user(id)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
        
    elif code == 1:#增加/删除管理员
        id = data.get('id_be_done')
        password = data.get('user_password')
        email = data.get('email')
        name = data.get('name')
        if password:
            sign = SCtr_Mana.email_id_exist(id,email)
            if sign:
                sign2 = SCtr_Mana.add_manager(id,password,name,email)
                if sign2:
                    return jsonify({"status":"successfully"})
                return jsonify({"status":"fail"})
            return jsonify({"status":"fail"})
        sign = SCtr_Mana.delete_user(id)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    
    user = Ctr_User_S.get_all_user()
    manager = SCtr_Mana.get_all_manager()
    return jsonify({"status":"successfully","user":user,"manager":manager})

#主界面
@app.route('/main_ui',methods = ['POST'])
@cross_origin()
@jwt_required()
def main_ui():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    more = data.get('more')
    if more:
        film_type = data.get("film_type")
        last_id = data.get('last_id')
        return jsonify({"more":SCtr_Film_M.get_more_films(film_type,last_id)})
    return SCtr_Film_M.get_film_info()

#获取当前用户/管理员/超管状态
@app.route('/user_infor',methods = ['POST'])
@cross_origin()
@jwt_required()
def user_infor():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code ==0:#超管
        infor = SCtr_Super.get_infor(user_id)
        if infor:
            togather = {}
            togather["user_today"]=user_today
            togather["user_regist"]=user_regist
            togather["manager_ban_block"]=manager_ban_block
            togather["user_ban_block"]=user_ban_block
            togather["film_love"]=film_love
            return jsonify({"status":"successfully","infor":infor,"togather":togather})
    elif code ==1:#用户
        infor = SCtr_User_M.get_infor(user_id)
        if infor:
            return jsonify({"status":"successfully","infor":infor})
    elif code == 2:#管理员
        infor = SCtr_Mana.get_infor(user_id)
        if infor:
            return jsonify({"status":"successfully","infor":infor})
    return jsonify({"status":"fail"})

#获取特定电影评论
@app.route('/comment',methods = ['POST'])
@cross_origin()
@jwt_required()
def comment():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    
    film_id = data.get('film_id')
    comment_type = data.get('type')
    last_assist = data.get('last_assist', None)
    last_id = data.get('last_id', None)


    result = {}
    if comment_type == 'all':
        comments_on_film,has_more_comment = SCtr_Comment_C.get_commentonfilm_by_film_id(film_id)
        mark_comments,has_more_mark = SCtr_Mark_C.get_markcommend_by_film_id(film_id)
        
        film = SCtr_Film_M.get_film_by_id(film_id)
        
        result = {
            "film":film,
            "commentonfilm": comments_on_film,
            "markcomment": [],
            "has_more_comment":has_more_comment,
            "has_more_mark":has_more_mark 
        }

        for mark_comment in mark_comments:
            mark_comment_value = mark_comment
            
            recomment_list,has_more_recomment = SCtr_Re_C.get_recomment_by_markcomment_id(mark_comment['mark_id'])
            result["markcomment"].append({
                "markcomment_value": mark_comment_value,
                "recomment": recomment_list,
                "has_more_recomment":has_more_recomment
            })
            
        
    elif comment_type == 'comment_on_film':
        comments_on_film, has_more = SCtr_Comment_C.get_commentonfilm_by_film_id(film_id, last_assist, last_id)
        result['commentonfilm'] = comments_on_film
        result['has_more'] = has_more
    elif comment_type == 'mark_commend':
        mark_comments, has_more = SCtr_Mark_C.get_markcommend_by_film_id(film_id, last_assist, last_id)
        result['markcomment'] = []
        for mark_comment in mark_comments:
            mark_comment_value = mark_comment
            recomment_list, re_has_more = SCtr_Re_C.get_recomment_by_markcomment_id(mark_comment['mark_id'])
            result['markcomment'].append({
                "markcomment_value": mark_comment_value,
                "recomment": recomment_list,
                "re_has_more": re_has_more
            })
        result['has_more'] = has_more
    elif comment_type == 'recomment':
        mark_id = data.get('mark_id')
        recomments, has_more = SCtr_Re_C.get_recomment_by_markcomment_id(mark_id, last_assist, last_id)
        result['recomment'] = recomments
        result['has_more'] = has_more
    else:
        return jsonify({'error': 'Invalid comment type'}), 400

    return jsonify(result)

#用户评论:用户的影评、评论、回复、推荐
@app.route('/user_comment',methods = ['POST'])
@cross_origin()
@jwt_required()
def user_comment():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code == 0:#影评
        content = data.get('content')
        sign = SCtr_Comment_W.add_comment(content['film_id'],content['user_id'],content['long_comment'],content['comment_date'])
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    elif code ==1:#短评
        content = data.get('content')
        sign = SCtr_Mark_W.add_mark(content['film_id'],content['user_id'],content['mark'],content['short_comment'])
        if sign:
            return jsonify({"status":"successfully"})
    elif code ==2:#回复
        content = data.get('content')
        sign = SCtr_Re_W.add_re(content['mark_id'],content['user_id'],content['recomment'])
        if sign:
            return jsonify({"status":"successfully"})
    elif code == 3:#推荐
        film_id = data.get('film_id')
        sign = SCtr_Film_C.assist_film(film_id)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
        

#评论状态更新:可以审核影评、置顶、点赞
@app.route('/comment_new',methods = ['POST'])
@cross_origin()
@jwt_required()
def comment_new():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    
    code = data.get('code')
    if code == 0:#更新影评状态
        film_comment_id = data.get('id')
        comment_assist=data.get('assist') 
        top_not=data.get('top') 
        comment_pass=data.get('comment_pass')
        sign = SCtr_Comment_C.update_comment_state(film_comment_id, comment_assist, top_not, comment_pass)
        if(sign):
            return jsonify({"statu":"update successfully"})
        return jsonify({"statu":"update fail"})
    elif code == 1:#更新短评状态
        mark_id=data.get('id')
        short_assist=data.get('assist')
        short_top_not=data.get('top')
        sign = SCtr_Mark_C.update_mark_state(mark_id, short_assist, short_top_not)
        if(sign):
            return jsonify({"statu":"update successfully"})
        return jsonify({"statu":"update fail"})
    elif code == 2:#更新回评状态
        recomment_id=data.get('id')
        re_assist=data.get('assist')
        re_top_not=data.get('top')
        sign = SCtr_Re_C.update_recomment_state(recomment_id, re_assist, re_top_not)
        if(sign):
            return jsonify({"statu":"update successfully"})
        return jsonify({"statu":"update fail"})

#管理员管理评论：可以删除影评、评论、回复，也可以获取未经审核的影评
@app.route('/manage_comment',methods = ['POST'])
@cross_origin()
@jwt_required()
def manage_comment():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    
    if code == 0:#获取未审核影评
        comments = SCtr_Comment_C.get_comment()
        if comments:
            return jsonify({"statu":"successfully","comments":comments})
        return jsonify({"statu":"fail"})
    elif code == 1:#管理员删除不良影评
        film_comment_id = data.get('id')
        sign = SCtr_Comment_C.delete_comment(film_comment_id)
        if(sign):
            return jsonify({"statu":"successfully"})
        return jsonify({"statu":"fail"})
    elif code == 2:#管理员删除不良短评
        mark_id = data.get('id')
        sign = SCtr_Mark_C.delete_mark(mark_id)
        if(sign):
            return jsonify({"statu":"successfully"})
        return jsonify({"statu":"fail"})
    elif code == 3:#管理员删除不良回复
        re_id = data.get('id')
        sign = SCtr_Re_C.delete_recomment(recomment_id=re_id)
        if(sign):
            return jsonify({"statu":"successfully"})
        return jsonify({"statu":"fail"})

#管理员禁言/封禁用户:管理员在此禁言/封禁、解禁用户
@app.route('/manage_user',methods = ['POST'])
@cross_origin()
@jwt_required()
def manage_user():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code == 1:#获取被禁言的用户
        manager_id = user_id
        users = SCtr_User_M.get_user_complan(manager_id)
        if users:
            return jsonify({"status":"successfully","users":users})
        return jsonify({"status":"fail"})
    user_be_done = data.get('user_be_done')
    content = data.get('content')#接受一个字典类型的数据 
    if content == None:
        return jsonify({"status":"fail"})
    sign = SCtr_User_M.ban_block_user(user_be_done,content)
    if sign:
        if user_be_done:
            global user_ban_block,manager_ban_block
            user_ban_block+=1
            manager_ban_block +=1
        return jsonify({"statu":"successfully"})
    return jsonify({"statu":"fail"})

#搜索功能
@app.route('/search',methods = ['POST'])
@cross_origin()
@jwt_required()
def search():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    search = data.get('search')
    sign = SCtr_Film_M.search_film(search)
    if sign:
        return jsonify({"status":"successfully","film":sign})
    return jsonify({"status":"fail"})
        
#用户关注列表:用户查看关注列表、取消关注、点击关注
@app.route('/user_love',methods = ['POST'])
@cross_origin()
@jwt_required()
def user_love():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code == 0:#用户点击关注
        film_id = data.get("film_id")
        sign = SCtr_Film_C.add_u_f(user_id,film_id)
        if sign:
            global film_love
            film_love +=1
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    elif code == 1:#用户取关
        film_id = data.get("film_id")
        sign = SCtr_Film_C.delete_u_f(user_id,film_id)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    films = SCtr_Film_C.get_love_film(user_id)
    if films:
        return jsonify({"status":"successfully","films":films})
    return jsonify({"status":"fail"})

#超管新增、修改、删除电影
@app.route('/super_film',methods = ['POST'])
@cross_origin()
@jwt_required()
def super_film():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    code = data.get('code')
    if code == 0:#新增电影
        film_name = data.get('film_name')
        actor = data.get('actor')
        director = data.get('director')
        release_time = data.get('release_time')
        introductory = data.get('introductory')
        www_http = data.get('www_http')
        sign = SCtr_Film_M.add_film(film_name, actor, director, release_time, introductory,www_http)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    elif code == 1:#删除电影
        film_id = data.get('film_id')
        sign = SCtr_Film_M.delete_film(film_id)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})
    elif code == 2:#修改电影
        film_id = data.get('film_id')
        content = data.get('content')
        sign = SCtr_Film_M.update_film(film_id,content)
        if sign:
            return jsonify({"status":"successfully"})
        return jsonify({"status":"fail"})

#用户发起申诉
@app.route('/user_complain',methods = ['POST'])
@cross_origin()
@jwt_required()
def user_complain():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    complain = data.get('complain')
    sign = SCtr_User_M.user_complain(user_id,complain)
    if sign:
        return jsonify({"status":"successfully"})
    return jsonify({"status":"fail"})
    
#管理员：获取特定用户信息
@app.route('/infor_get',methods = ['POST'])
@cross_origin()
@jwt_required()
def infor_get():
    current_user = str(get_jwt_identity())# 获取token中的用户身份信息
    data = request.json
    user_id = data.get('user_id')
    if str(user_id) != current_user:
        return jsonify({'error': 'Access denied'}), 403
    id = data.get("get_id")
    infor = SCtr_User_M.get_infor(id)
    if infor:
        return jsonify({"status":"successfully","infor":infor})
    return jsonify({"status":"fail"})

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=5000)
